<?php
// $Id: matchdart.admin.inc 182 2010-03-13 17:49:35Z mwi.nor $

/**
 * @file
 * Administrative page callbacks for the matchdart module.
 */

function matchdart_form_main($type, $edit = array()) {
  if ((isset($_POST['op']) && $_POST['op'] == t('Delete')) || !empty($_POST['confirm'])) {
    return drupal_get_form('matchdart_confirm_delete', $edit['tid']);
  }
  switch ($type) {
    case 'series':
      return drupal_get_form('matchdart_form_series', $edit);
      break;
    case 'event':
      return drupal_get_form('matchdart_form_event', $edit);
      break;
  }
}

/**
 * Returns a form for adding an event to the matchdart vocabulary
 *
 * @param $edit Associative array containing an event term to be added or edited.
 * @ingroup forms
 * @see matchdart_form_submit()
 */
function matchdart_form_event(&$form_state, $edit = array()) {
  $edit += array(
    'name' => '',
    'description' => '',
    'tid' => NULL,
    'weight' => 0,
  );
  $form['name'] = array('#type' => 'textfield',
    '#title' => t('Event name'),
    '#default_value' => $edit['name'],
    '#maxlength' => 255,
    '#description' => t('Name for the darts event.'),
    '#required' => TRUE,
  );
  $form['description'] = array('#type' => 'textarea',
    '#title' => t('Description'),
    '#default_value' => $edit['description'],
    '#description' => t('Description for the event.'),
  );
  $form['parent']['#tree'] = TRUE;
  $form['parent'][0] = _matchdart_parent_select($edit['tid'], t('Parent'), 'event');
  $form['weight'] = array('#type' => 'weight',
    '#title' => t('Weight'),
    '#default_value' => $edit['weight'],
    '#description' => t('Events are displayed in ascending order by weight (events with equal weights are displayed alphabetically).'),
  );

  $form['vid'] = array('#type' => 'hidden', '#value' => variable_get('matchdart_event_vocabulary', ''));
  $form['submit' ] = array('#type' => 'submit', '#value' => t('Save'));
  if ($edit['tid']) {
    $form['delete'] = array('#type' => 'submit', '#value' => t('Delete'));
    $form['tid'] = array('#type' => 'hidden', '#value' => $edit['tid']);
  }
  $form['#submit'][] = 'matchdart_form_submit';
  $form['#theme'] = 'matchdart_form';

  return $form;
}

/**
 * Returns a form for adding a series to the matchdart vocabulary
 *
 * @param $edit Associative array containing a series term to be added or edited.
 * @ingroup forms
 * @see matchdart_form_submit()
 */
function matchdart_form_series(&$form_state, $edit = array()) {
  $edit += array(
    'name' => '',
    'description' => '',
    'tid' => NULL,
    'weight' => 0,
  );
  // Handle a delete operation.
  $form['name'] = array(
    '#title' => t('Series name'),
    '#type' => 'textfield',
    '#default_value' => $edit['name'],
    '#maxlength' => 255,
    '#description' => t('Name for the darts event series.'),
    '#required' => TRUE
  );

  $form['description'] = array(
    '#type' => 'textarea',
    '#title' => t('Description'),
    '#default_value' => $edit['description'],
    '#description' => t('Description for the darts event series.')
  );
//  $form['parent']['#tree'] = TRUE;
//  $form['parent'][0] = _matchdart_parent_select($edit['tid'], t('Parent'), 'series');
  $form['weight'] = array(
    '#type' => 'weight',
    '#title' => t('Weight'),
    '#default_value' => $edit['weight'],
    '#description' => t('Series are displayed in ascending order by weight (series with equal weights are displayed alphabetically).')
  );

  $form['vid'] = array(
    '#type' => 'hidden',
    '#value' => variable_get('matchdart_event_vocabulary', ''),
  );
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Save')
  );
  if ($edit['tid']) {
    $form['delete'] = array('#type' => 'submit', '#value' => t('Delete'));
    $form['tid'] = array('#type' => 'value', '#value' => $edit['tid']);
  }
  $form['#submit'][] = 'matchdart_form_submit';
  $form['#theme'] = 'matchdart_form';

  return $form;
}

/**
 * Process season form and event form submissions.
 */
function matchdart_form_submit($form, &$form_state) {
  if ($form['form_id']['#value'] == 'matchdart_form_series') {
    $tseries = TRUE;
    $type = t('series');
  }
  else {
    $tseries = FALSE;
    $type = t('event');
  }

  $status = taxonomy_save_term($form_state['values']);
  switch ($status) {
    case SAVED_NEW:
      if ($tseries) {
        $series = variable_get('matchdart_series', array());
        $series[] = $form_state['values']['tid'];
        variable_set('matchdart_series', $series);
      }
      drupal_set_message(t('Created new @type %term.', array('%term' => $form_state['values']['name'], '@type' => $type)));
      break;
    case SAVED_UPDATED:
      drupal_set_message(t('The @type %term has been updated.', array('%term' => $form_state['values']['name'], '@type' => $type)));
      break;
  }
  $form_state['redirect'] = 'admin/content/matchdart';
  return;
}

/**
 * Returns a confirmation page for deleting a matchdart taxonomy term.
 *
 * @param $tid ID of the term to be deleted
 */
function matchdart_confirm_delete(&$form_state, $tid) {
  $term = taxonomy_get_term($tid);

  $form['tid'] = array('#type' => 'value', '#value' => $tid);
  $form['name'] = array('#type' => 'value', '#value' => $term->name);

  return confirm_form($form, t('Are you sure you want to delete the matchdart %name?', array('%name' => $term->name)), 'admin/content/matchdart', t('Deleting a season or event will also delete childs, if any. To delete matches in this event/season, visit <a href="@content">content administration</a> first. This action cannot be undone.', array('@content' => url('admin/content/node'))), t('Delete'), t('Cancel'));
}

/**
 * Implementation of forms api _submit call. Deletes a season after confirmation.
 */
function matchdart_confirm_delete_submit($form, &$form_state) {
  taxonomy_del_term($form_state['values']['tid']);
  drupal_set_message(t('The series/event %term and all childs and associated matches have been deleted.', array('%term' => $form_state['values']['name'])));
  watchdog('content', 'matchdart: deleted %term and all its childs and associated matches.', array('%term' => $form_state['values']['name']));

  $form_state['redirect'] = 'admin/content/matchdart';
  return;
}

/**
 * Form builder for the matchdart settings page.
 *
 * @see system_settings_form()
 */
function matchdart_admin_settings() {
  $form = array();
  
  $form['matchdart_myplayercolor'] = array(
    '#type' => 'textfield',
    '#title' => t('Highlight color'),
    '#default_value' => variable_get('matchdart_myplayercolor', '#FF0000'),
    '#size' => 10,
    '#maxlength' => 7,
    '#description' => t("The color to highlight own player in tables [#hex]."),
    '#required' => TRUE,
  );

  $form['matchdart_pointswin'] = array(
    '#type' => 'textfield',
    '#title' => t('Points for win'),
    '#default_value' => variable_get('matchdart_pointswin', '3'),
    '#size' => 5,
    '#maxlength' => 3,
    '#description' => t("The number of points for a win."),
    '#required' => TRUE,
  );
  
  $form['matchdart_pointsdraw'] = array(
    '#type' => 'textfield',
    '#title' => t('Points for draw'),
    '#default_value' => variable_get('matchdart_pointsdraw', '1'),
    '#size' => 5,
    '#maxlength' => 3,
    '#description' => t("The number of points for a draw."),
    '#required' => TRUE,
  );
  
  $form['matchdart_pointslose'] = array(
    '#type' => 'textfield',
    '#title' => t('Points for lose'),
    '#default_value' => variable_get('matchdart_pointslose', '0'),
    '#size' => 5,
    '#maxlength' => 3,
    '#description' => t("The number of points for a lose."),
    '#required' => TRUE,
  );
  
  $form['matchdart_drawlines'] = array(
    '#type' => 'textfield',
    '#title' => t('Draw line after position(s)'),
    '#default_value' => variable_get('matchdart_drawlines', ''),
    '#size' => 20,
    '#maxlength' => 16,
    '#description' => t("Comma separated list of positions."),
    '#required' => FALSE,
  );
  
  // examples for control fields taken from forum module

//  select box
//  $number = drupal_map_assoc(array(5, 10, 15, 20, 25, 30, 35, 40, 50, 60, 80, 100, 150, 200, 250, 300, 350, 400, 500));
//  $form['matchdart_hot_topic'] = array('#type' => 'select',
//    '#title' => t('Hot topic threshold'),
//    '#default_value' => variable_get('matchdart_hot_topic', 15),
//    '#options' => $number,
//    '#description' => t('The number of posts a topic must have to be considered "hot".'),
//  );

//  radio buttons
//  $forder = array(1 => t('Date - newest first'), 2 => t('Date - oldest first'), 3 => t('Posts - most active first'), 4 => t('Posts - least active first'));
//  $form['matchdart_order'] = array('#type' => 'radios',
//    '#title' => t('Default order'),
//    '#default_value' => variable_get('matchdart_order', '1'),
//    '#options' => $forder,
//    '#description' => t('Default display order for topics.'),
//  );
  return system_settings_form($form);
}

/**
 * Admin form validation
 * [module]_[formname]_validate --> drupal executes automatically after submitting the form
 * @return error if the user input is not valid
 */
function matchdart_admin_validate($form, &$form_state) {
  $myplayercolor = $form_state['values']['matchdart_myplayercolor'];
  if (substr($myplayercolor,0,1)<>'#') {
    form_set_error('matchdart_myplayercolor', t('You must enter a hex value prefixed by "#" for the highlighting color.'));
  }
//  else if ($myplayercolor <= 0) {
//    form_set_error('matchdart_maxdisp', t('Maximum number of links must be positive.'));
//  }
}


/**
 * Returns an overview list of existing series and events
 */
function matchdart_overview(&$form_state) {
  module_load_include('inc', 'taxonomy', 'taxonomy.admin');

  $vid = variable_get('matchdart_event_vocabulary', '');
  $vocabulary = taxonomy_vocabulary_load($vid);
  $form = taxonomy_overview_terms($form_state, $vocabulary);

  foreach (element_children($form) as $key) {
    if (isset($form[$key]['#term'])) {
      $term = $form[$key]['#term'];
      $form[$key]['view']['#value'] = l($term['name'], 'matchdart/'. $term['tid']);
      if (in_array($form[$key]['#term']['tid'], variable_get('matchdart_series', array()))) {
        $form[$key]['edit']['#value'] = l(t('edit series'), 'admin/content/matchdart/edit/series/'. $term['tid']);
      }
      else {
        $form[$key]['edit']['#value'] = l(t('edit event'), 'admin/content/matchdart/edit/event/'. $term['tid']);
      }
    }
  }

  // Remove the alphabetical reset.
  unset($form['reset_alphabetical']);

  // The form needs to have submit and validate handlers set explicitly.
  $form['#theme'] = 'taxonomy_overview_terms';
  $form['#submit'] = array('taxonomy_overview_terms_submit'); // Use the existing taxonomy overview submit handler.
  $form['#validate'] = array('taxonomy_overview_terms_validate');
  $form['#empty_text'] = '<em>'. t('There are no existing series or events. Series and events may be added using the <a href="@series">add series</a> and <a href="@event">add event</a> pages.', array('@series' => url('admin/content/matchdart/add/series'), '@event' => url('admin/content/matchdart/add/event'))) .'</em>';
  return $form;
}

/**
 * Returns a select box for available parent terms
 *
 * @param $tid ID of the term which is being added or edited
 * @param $title Title to display the select box with
 * @param $child_type Whether the child is forum or container
 */
function _matchdart_parent_select($tid, $title, $child_type) {

  $parents = taxonomy_get_parents($tid);
  if ($parents) {
    $parent = array_shift($parents);
    $parent = $parent->tid;
  }
  else {
    $parent = 0;
  }

  $vid = variable_get('matchdart_event_vocabulary', '');
  $children = taxonomy_get_tree($vid, $tid);

  // A term can't be the child of itself, nor of its children.
  foreach ($children as $child) {
    $exclude[] = $child->tid;
  }
  $exclude[] = $tid;

  $tree = taxonomy_get_tree($vid);
  $options[0] = '<'. t('root') .'>';
  if ($tree) {
    foreach ($tree as $term) {
      if (in_array($term->tid, variable_get('matchdart_series', array()))) {
          if (!in_array($term->tid, $exclude)) {
            $options[$term->tid] = str_repeat(' -- ', $term->depth) . $term->name;
          }
      }
    }
  }
  if ($child_type == 'series') {
    $description = t('Series are usually placed at the top (root) level, but may also be placed inside another series or forum.');
  }
  else if ($child_type == 'event') {
    $description = t('Events may be placed at the top (root) level, or inside a series.');
  }

  return array('#type' => 'select', '#title' => $title, '#default_value' => $parent, '#options' => $options, '#description' => $description, '#required' => TRUE);
}
